package com.rivulet.foreign.controller;

import com.rivulet.foreign.pojo.UserInformation;
import com.rivulet.foreign.service.ToolService;
import com.rivulet.foreign.service.UserService;
import com.rivulet.foreign.tools.FileTool;
import com.rivulet.foreign.tools.Lock;
import com.rivulet.foreign.tools.Results;
import com.rivulet.foreign.tools.TimeTool;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import static com.rivulet.foreign.tools.Identity.STUDENT;

/**
 * {个人信息管理}
 *
 * @author xujiac
 * @create 2021/8/19
 * @since 1.0.0
 */
@Controller
public class ManagerController {
    @Value("${filepath}")
    String fileDirPath;
    final ToolService authorizationForIdentity;
    final UserService userService;

    public ManagerController(ToolService authorizationForIdentity,UserService userService) {
        this.authorizationForIdentity = authorizationForIdentity;
        this.userService=userService;
    }

    @RequestMapping(value = "/setInformation", method = RequestMethod.POST)
    @ResponseBody
    public Results setInformation(@RequestBody UserInformation map, @CookieValue(value = "user_id", defaultValue = "0") String student_id) {
        if (!authorizationForIdentity.reAuthorization(student_id, STUDENT)) {
            return null;
        }
        map.setUser_id(Lock.lockOff(student_id));
        Results<Object> results = userService.setInformation(map);
        return results;
    }

    @RequestMapping(value = "/information/download")
    public Results informationDownLoad(HttpServletResponse response, @CookieValue(value = "user_id", defaultValue = "0") String user_id) throws IOException {
        if (!authorizationForIdentity.reAuthorization(user_id, 5)) {
            return null;
        }
        Results<List<UserInformation>> results = userService.getAllInformation();
        List<UserInformation> list = results.getData();

        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        HSSFSheet sheet = hssfWorkbook.createSheet("学生基本信息表");
        String filename = "userInfo.xls";

        String[] headers = {"学号", "护照姓名", "中文名", "学生类别", "国籍", "性别",
                "出生年月", "宿舍", "班级", "入学时间", "离校时间", "护照号", "护照到期时间",
                "签证号", "签证到期时间", "保险到期时间", "经费类别", "专业",
                "宗教信仰", "获奖信息", "手机联系方式", "微信号", "邮箱"};
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        int rowNum = 1;
        for (UserInformation userInformation : list) {
            HSSFRow rows = sheet.createRow(rowNum);
            try {
                rows.createCell(0).setCellValue(userInformation.getUser_id().toString());
                rows.createCell(1).setCellValue(userInformation.getPassport_name());
                rows.createCell(2).setCellValue(userInformation.getChinese_name());
                rows.createCell(3).setCellValue(userInformation.getStudent_type());
                rows.createCell(4).setCellValue(userInformation.getCitizenship());
                if (userInformation.getSex() == 1) {
                    rows.createCell(5).setCellValue("男");
                }
                if (userInformation.getSex() == 0) {
                    rows.createCell(5).setCellValue("女");
                }
                if (userInformation.getSex() == -1){
                    rows.createCell(5).setCellValue("其他");
                }
                rows.createCell(6).setCellValue(TimeTool.DateToStringYM(userInformation.getBirth_date()));
                rows.createCell(7).setCellValue(userInformation.getDormitory());
                rows.createCell(8).setCellValue(userInformation.getClasses());
                rows.createCell(9).setCellValue(TimeTool.DateToString(userInformation.getStart_school_time()));
                rows.createCell(10).setCellValue(TimeTool.DateToString(userInformation.getLeave_school_time()));
                rows.createCell(11).setCellValue(userInformation.getPassport_id());
                rows.createCell(12).setCellValue(TimeTool.DateToString(userInformation.getPassport_end_time()));
                rows.createCell(13).setCellValue(userInformation.getVisa_id());
                rows.createCell(14).setCellValue(TimeTool.DateToString(userInformation.getVisa_end_time()));
                rows.createCell(15).setCellValue(TimeTool.DateToString(userInformation.getInsurance_end_time()));
                rows.createCell(16).setCellValue(userInformation.getExpenditure_type());
                rows.createCell(17).setCellValue(userInformation.getMajor());
                rows.createCell(18).setCellValue(userInformation.getReligion());
                rows.createCell(19).setCellValue(userInformation.getWinning_information());
                rows.createCell(20).setCellValue(userInformation.getPhone_number());
                rows.createCell(21).setCellValue(userInformation.getWeChat());
                rows.createCell(22).setCellValue(userInformation.getEmail());
            } catch (Exception e) {
                System.out.println(e.toString());
            }
            rowNum++;
        }
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + filename);
        response.flushBuffer();
        hssfWorkbook.write(response.getOutputStream());
        return null;
    }

    @RequestMapping(value = "/getImage")
    public void getImage(@CookieValue(value = "user_id") String user_id,HttpServletResponse response){
        String filepath=fileDirPath + "a_user_picture" + File.separator + Lock.lockOff(user_id) + ".png";
        File file = new File(filepath);
        if (!file.exists()) {
            filepath=fileDirPath + "user_image.png";
        }
        try {
            BufferedImage image = FileTool.getInputStream(filepath);
            if(image==null){
                throw new Exception("图片打印异常："+filepath);
            }else {
                ImageIO.write(image,"png",response.getOutputStream());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @ResponseBody
    @RequestMapping(value = "/setUserPicture")
    public Results setPicture(@CookieValue("user_id")String user_id ,@RequestParam("user_picture") MultipartFile file){
        Results results=new Results(400,null);
        if(file.getSize()>1024*1024){
            results.setMsg("文件大小超过传输限制！");
            return  results;
        }
        if(FileTool.pictureSave(fileDirPath,Lock.lockOff(user_id),file)){
            results.setCode(100);
        }else {
            results.setMsg("请检查是否上传了正确的头像格式");
        }
        return results;
    }
}
